from __future__ import absolute_import
import os
import os.path
import glob
import logging
from os.path import isdir #, join
from forest.registry import register_tool
from forest.tool import Tool

logger = logging.getLogger('forest.tools.system.chmod')

def joinpaths(*args, **kwargs):
    path = os.path.sep.join(args)

    if kwargs.get("follow_symlinks"):
        return os.path.realpath(path)
    else:
        return path

@register_tool('system.chmod')
def chmod(path, mode, recursive=False):
    Tool.SIGNAL_TOOL_START(chmod, level = logging.DEBUG, message = 'Chmod: %s %s recursive: %s' % (path, mode, recursive))

    for fname in glob.iglob(path):
        os.chmod(fname, mode)

        if recursive and isdir(fname):
            for nested in os.listdir(fname):
                nested = joinpaths(fname, nested)
                chmod(nested, mode, recursive)
